package org.p2psimulator.entity.protocol.structured.chordcycles;

import java.util.List;

import org.p2psimulator.entity.Id;
import org.p2psimulator.entity.Peer;
import org.p2psimulator.entity.filesystem.FileSystem;
import org.p2psimulator.entity.overlaynetwork.routingtable.ChordFingerTable;
import org.p2psimulator.entity.protocol.messages.chord.ChordFileOwner;
import org.p2psimulator.engine.Environment;

public class ChordKeyDistCycle extends ChordCycle {

    public ChordKeyDistCycle(Environment env, int transId) {
        super(env, transId);
    }

    @Override
    public String runRequestCycle(Peer p) {

        FileSystem fsys = env.getFileSystem();

        List<Id> files = fsys.getPeerFiles(p.getId());

        for (Id key : files) {

            ChordFingerTable table = getFingerTable(p);
            Id closestPreceeding = table.getClosestPreceding(key);
            Double d = (Double) closestPreceeding.getValue();
            if (d.isNaN()) {
                closestPreceeding = table.getSucessor();
            }
            if (closestPreceeding==null){
               Id k = env.getPeerBank().getRandomPeer().getId();
               closestPreceeding = k;
            }
            ChordFileOwner msg = new ChordFileOwner(p.getId(),
                    closestPreceeding, currentTransactionId, p.getBehavior().getBehaviorType());

            msg.setTTL(15);
            msg.setHOP(0);
            msg.setServentId(p.getId());
            msg.setFileKey(key);

            env.getNetwork().sendMessage(msg);
        }

        StringBuilder str = new StringBuilder("  [KEY DIST CYCLE]   -   "
                + " [CHORDFILEOWNER enviadas: " + files.size() + "]");
        return str.toString();
    }

    @Override
    public String runResponseCycle(Peer p) {
        return "";
    }

    @Override
    public String runSecondRequestCycle(Peer p) {
        return "";
    }

    @Override
    public String runSecondResponseCycle(Peer p) {
        return "";
    }
}
